package com.hatricks.is.jvm;

import lombok.SneakyThrows;

import java.io.RandomAccessFile;
import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;

/**
 * @packageName: com.hatricks.is.jvm
 * @className: DirectAndMappedTest
 * @author: yanyuhui y568821795@outlook.com
 * @date: 2024-12-11 16:35
 * @description: 堆外和mapped内存测试
 */
public class DirectAndMappedTest {

    @SneakyThrows
    public static void main(String[] args) {

        // 创建直接缓冲区
        ByteBuffer directBuffer = ByteBuffer.allocateDirect(1024 * 1024); // 1MB direct buffer
        // 使用内存映射文件
        try (RandomAccessFile file = new RandomAccessFile("temp.dat", "rw");
             FileChannel channel = file.getChannel()) {
            MappedByteBuffer mappedBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024 * 1024); // 1MB mapped buffer
        }

        // 获取所有缓冲池MXBean
        List<BufferPoolMXBean> pools = ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
        // 遍历缓冲池MXBean列表
        for (BufferPoolMXBean pool : pools) {
            // 打印缓冲池名称
            System.out.println("Buffer Pool Name: " + pool.getName());
            // 打印缓冲池当前使用的内存量
            System.out.println("Count of Buffers: " + pool.getCount());
            // 打印缓冲池当前使用的内存量
            System.out.println("Memory Used: " + pool.getMemoryUsed() + " bytes");
            // 打印缓冲池能够使用的最大内存量
            System.out.println("Total Capacity: " + pool.getTotalCapacity() + " bytes");
            // 打印一个分隔符
            System.out.println("-----------------------------------");
        }
    }

}
